#include <Driver.h>

#include <curl/curl.h>

#include <stdexcept>

#include <sstream>

namespace{
    size_t nullwriter( void *ptr, size_t size, size_t nmemb, void *userdata){
        return size * nmemb;
    }
    bool is_alive(const CExpert::DBChecker::conn_params& cp){
        CURL* handle = curl_easy_init();
        if (!handle)
            throw std::runtime_error("can't init cURL");
        //TODO: check result codes
        curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 1);
        std::stringstream stream;
        stream << "http://" << cp.host << ":" << ((cp.port.empty() || cp.port == "0") ? "80" : cp.port) << "/";
        if (!cp.db.empty())
            stream << cp.db;

        std::string url(stream.str());
        //std::cout << url << std::endl;
        curl_easy_setopt(handle, CURLOPT_VERBOSE, 0);
        curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, &nullwriter);
        curl_easy_setopt(handle, CURLOPT_URL, url.c_str());
        curl_easy_setopt(handle, CURLOPT_USERAGENT, "cexpert http plugin (cURL powered)");
        curl_easy_setopt(handle, CURLOPT_HTTPGET, 1);
        curl_easy_setopt(handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_easy_setopt(handle, CURLOPT_TIMEOUT, 1); //0.5s
        curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, 1); //0.5s

        long retcode = 0;
        CURLcode result = curl_easy_perform(handle);
        if (result == 0){
            //std::cout << "performed" << std::endl;
            curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &retcode);
        } else{
            //std::cout << curl_easy_strerror(result) << std::endl;
        }
        curl_easy_cleanup(handle);
        //std::cout << retcode << std::endl;
        return (retcode >= 200 && retcode < 300);
    }
}
void http_init(){
    static int http_init_v = CExpert::register_driver("http", &is_alive);
    (void)http_init_v;
}
